const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');
const dbConfig = require('./config');

async function createMerchantsTable() {
  try {
    // 读取SQL文件
    const sqlFile = path.join(__dirname, 'create_merchants_table.sql');
    const sqlContent = fs.readFileSync(sqlFile, 'utf8');
    
    // 连接数据库
    const connection = await mysql.createConnection(dbConfig);
    console.log('✅ 数据库连接成功');
    
    // 执行SQL语句
    const statements = sqlContent.split(';').filter(stmt => stmt.trim());
    
    for (const statement of statements) {
      if (statement.trim()) {
        try {
          await connection.execute(statement);
          console.log('✅ 执行SQL语句成功');
        } catch (error) {
          if (error.code === 'ER_TABLE_EXISTS_ERROR') {
            console.log('ℹ️ 表已存在，跳过创建');
          } else {
            console.error('❌ 执行SQL语句失败:', error.message);
          }
        }
      }
    }
    
    // 验证表是否创建成功
    const [tables] = await connection.execute('SHOW TABLES LIKE "merchants"');
    if (tables.length > 0) {
      console.log('✅ merchants表创建成功');
      
      // 检查表结构
      const [columns] = await connection.execute('DESCRIBE merchants');
      console.log('📋 merchants表结构:');
      columns.forEach(col => {
        console.log(`  - ${col.Field}: ${col.Type}`);
      });
      
      // 检查数据
      const [data] = await connection.execute('SELECT COUNT(*) as count FROM merchants');
      console.log(`📊 merchants表数据条数: ${data[0].count}`);
      
    } else {
      console.log('❌ merchants表创建失败');
    }
    
    await connection.end();
    
  } catch (error) {
    console.error('❌ 创建merchants表失败:', error);
  }
}

createMerchantsTable();
